package com.tuling.JUC;

import org.springframework.data.redis.connection.ReactiveZSetCommands;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class WheelBrokingQueue<T> implements BrokingQueue{
    //并发控制
    private Lock lock = new ReentrantLock();
    //判断是不是已经满了 如果已经满了阻塞
    Condition fullCondition = lock.newCondition();
    //判断是不是以及那个空了 如果空了阻塞
    Condition emptyCondition = lock.newCondition();

    private Object[] queue;
    private int size,count, putStr , takeStr;


    @Override
    public void put(Object element) throws InterruptedException {
        lock.lock();
        try {
            //判断是不是已经满了
            if(queue.length == size){
                fullCondition.await();
            }
            queue[putStr] = element;
            putStr ++;
            count ++;
            emptyCondition.signal();

        }finally {
            lock.unlock();
        }
    }

    @Override
    public T take() throws InterruptedException {
        lock.lock();
        try {
            //判断是不是有数据
            if(count == 0){
                emptyCondition.await();
            }
            T e = (T)queue[takeStr];
            takeStr ++;
            count --;

            fullCondition.signal();
            return e;
        }finally {
            lock.unlock();
        }


    }
}
